package frame.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import frame.pojo.Configuration;
import frame.io.Resources;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * FileName: XMLConfiguratorBuilder
 * Author:   xuan zongjun
 * Date:     2020/11/6 11:57
 * Description: 解析数据源的xml
 */


public class XMLConfiguratorBuilder {
    private Configuration configuration;

    public XMLConfiguratorBuilder(){
        this.configuration = new Configuration();
    }

    /**
     * 读取xml 配置文件
     * @param inputStream
     * @return
     */
    public Configuration parseConfiguration(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        //读取数据库的配置信息
        Document document = new SAXReader().read( inputStream );
        Element rootElement = document.getRootElement();
        // property 前面的 // 表示在xml中任意地方都可以获取到
        List<Element> propertyElements = rootElement.selectNodes( "//property" );
        Properties properties = new Properties(  );

        for (Element propertyElement : propertyElements) {
            String name = propertyElement.attributeValue( "name" );
            String value = propertyElement.attributeValue( "value" );
            properties.put( name,value );
        }

        //连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass( properties.getProperty( "driverClass" ) );
        comboPooledDataSource.setJdbcUrl( properties.getProperty( "url" ) );
        comboPooledDataSource.setUser( properties.getProperty( "username" ) );
        comboPooledDataSource.setPassword( properties.getProperty( "password" ) );

        //填充 configuration
        configuration.setDataSource( comboPooledDataSource );

        //mapper 部分
        List<Element> mapperElements = rootElement.selectNodes( "//mapper" );
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        for (Element mapperElement : mapperElements) {
            String mapperPath = mapperElement.attributeValue( "resource" );
            InputStream resourceAsSteam = Resources.getResourceAsSteam( mapperPath );
            xmlMapperBuilder.parse(resourceAsSteam);
        }

        return configuration;
    }


}
